package com.doris.lucene;

import java.io.IOException;
import java.util.concurrent.BlockingQueue;

import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.IndexWriter;

/**
 * 写索引线程，不允许多线程
 * 
 * @author root
 *
 */
public class DocumentIndexThread extends Thread {

	private static final Logger LOGGER = Logger.getLogger(DocumentIndexThread.class);
	private IndexWriter writer;
	/**
	 * 全部文档是否已经扫描完毕
	 */
	private volatile boolean isFinished = false;
	
	public DocumentIndexThread(IndexWriter writer) {
		this.writer = writer;
	}

	@Override
	public void run() {
		Thread.currentThread().setName("DocumentIndexThread");
		while (!isFinished) {
			if (!LuceneIndexer.getQueues().isEmpty()) {
				writeIndex();
			}
		}
		while (!LuceneIndexer.getQueues().isEmpty()) {
			writeIndex();
		}
		try {
			if (writer != null) {
				writer.close();
			}
		} catch (IOException e) {
			LOGGER.error("无法停止写索引", e);
		}
		LOGGER.info("DocumentIndexThread stopped!");
	}

	private void writeIndex() {
		try {
			BlockingQueue<LuceneDocument> queues = LuceneIndexer.getQueues();
			LuceneDocument docuemnt = queues.take();
			LOGGER.debug("index file " + docuemnt.getPath());
			String content = docuemnt.getContent();
			if (content == null) {
				return;
			}
			Document doc = new Document();
			doc.add(new StringField("name", docuemnt.getName(), Store.YES));
			doc.add(new StringField("path", docuemnt.getPath(), Store.YES));
			doc.add(new TextField("content", content, Store.YES));
			writer.addDocument(doc);
			Thread.sleep(100);
		} catch (IOException | InterruptedException e) {
			LOGGER.error("写索引失败", e);
		}
	}

	/**
	 * 本次索引的文档已经解析完成
	 */
	public void finish() {
		isFinished = true;
	}

}
